package com.firexxx.vp.domain.stb;

import com.firexxx.vp.domain.DomainConstants;
import com.firexxx.vp.domain.audio.AudioEntity;
import com.firexxx.vp.domain.audio.query.AudioQueryInterface;
import com.firexxx.vp.domain.vp.VoicePrintModel;
import com.firexxx.vp.domain.vp.VoicePrintResourceType;
import com.firexxx.vp.domain.vp.VoicePrintService;
import com.firexxx.vp.domain.vp.fuse.FuseVoicePrintEntity;
import com.firexxx.vp.domain.vp.query.VoicePrintModelQueryInterface;
import com.firexxx.vp.domain.vp.single.SingleVoicePrintEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @description: TODO
 * @throws:
 * @author: zhuangzhang2
 * @date: 2020/02/15 18:02
 */
@Service
@Slf4j
public class StbService {

    @Autowired
    private VoicePrintService vpService;

    @Autowired
    private VoicePrintModelQueryInterface voicePrintModelQueryInterface;

    @Autowired
    private AudioQueryInterface audioQueryInterface;

    @Autowired
    private DomainConstants constants;

    public VoicePrintModel match(StbEntity stbEntity, SingleVoicePrintEntity singleVoicePrintEntity) throws Throwable {
        singleVoicePrintEntity.extractVoicePrint(VoicePrintResourceType.PLPPNCC);

        if (CollectionUtils.isEmpty(stbEntity.getUserIdList())) {
            log.info("stb:{}未发现注册用户", stbEntity.getStbKey());

            return singleVoicePrintEntity.getVpModel();
        }

        List<VoicePrintModel> voicePrintModelList = voicePrintModelQueryInterface
                .findByVpIdList(stbEntity.getUserIdList());

        //声纹匹配
        VoicePrintModel matchVoicePrintModel = vpService.match(singleVoicePrintEntity.getVpModel(), voicePrintModelList, constants.getScoreThreshold());

        //返回
        if (matchVoicePrintModel != null) {
            log.info("stb:{}发现匹配的声纹{}", stbEntity.getStbKey(), matchVoicePrintModel.getVpId());

            return matchVoicePrintModel;
        } else {
            log.info("stb:{}未发现匹配的声纹", stbEntity.getStbKey());

            return singleVoicePrintEntity.getVpModel();
        }
    }

    public List<FuseVoicePrintEntity> clusterByAudioGroup(String groupId, StbEntity stbEntity) throws Throwable {
        List<AudioEntity> audioEntityList = audioQueryInterface
                .findAllByStbKey(stbEntity.getStbKey());

        if (CollectionUtils.isEmpty(audioEntityList)) {
            log.info("stb:{}未找到音频", stbEntity.getStbKey());

            return null;
        }

        List<FuseVoicePrintEntity> fuseVoicePrintEntityList = vpService.clusterByAudioGroup(groupId, audioEntityList);

        return fuseVoicePrintEntityList;
    }

}